#include <iostream>
#include <sys/select.h>
#include <string>
#include "socket.hpp"
using namespace socket_ns;

class SelectServer
{
    const static int gnum = sizeof(fd_set) * 8;
    const static int gdefaultfd = -1;

public:
    SelectServer(uint16_t port)
        : _port(port), _listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildListenSocket(_port);
    }
    ~SelectServer()
    {
    }
    void Init()
    {
        for (int i = 0; i < gnum; i++)
        {
            _select_array[i] = gdefaultfd;
        }
        _select_array[0] = _listensock->Sockfd();
    }

    void Accepter()
    {
        InetAddr addr;
        int sockfd = _listensock->Accepter(&addr);
        if (sockfd > 0)
        {
            LOG(DEBUG, "get a new link, client info %s:%d\n", addr.IP().c_str(), addr.Port());
            // 将sockfd添加到select辅助数组中
            bool flag = false;
            for (int pos = 1; pos < gnum; pos++)
            {
                if (_select_array[pos] == gdefaultfd)
                {
                    flag = true;
                    _select_array[pos] = sockfd;
                    LOG(INFO, "add %d to fd_array success!\n", sockfd);
                    break;
                }
            }
            // select可以等待的fd是有限的
            if (!flag)
            {
                LOG(WARNING, "Server Is Full!\n");
                ::close(sockfd);
            }
        }
    }

    void HanderIO(int i)
    {
        char buffer[1024];
        ssize_t n = ::recv(_select_array[i], buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say# " << buffer << std::endl;

            std::string responsestr = "HTTP/1.1 200 OK\r\n";
            responsestr += "Content-Type: text/html\r\n";
            responsestr += "\r\n";
            responsestr += "<html><h1>hello Linux</h1></html>";
            ::send(_select_array[i], responsestr.c_str(), responsestr.size(), 0);
        }
        else if (n == 0)
        {
            LOG(INFO, "client quit...\n");
            // 关闭fd
            ::close(_select_array[i]);
            // select 不要在关心这个fd了
            _select_array[i] = gdefaultfd;
        }
        else
        {
            LOG(ERROR, "recv error\n");
            // 关闭fd
            ::close(_select_array[i]);
            // select 不要在关心这个fd了
            _select_array[i] = gdefaultfd;
        }
    }
    void HandlerEvent(fd_set rfds)
    {
        //事件派发（遍历rfds看哪些fd就绪了，根据fd不同的类型处理不同的事件）
        for (int i = 0; i < gnum; i++)
        {
            if (_select_array[i] == gdefaultfd)
                continue;
            // 是关心的fd，但不一定就绪了，接下来检测他是否在rfds中
            if (FD_ISSET(_select_array[i], &rfds))
            {
                // 检测是listenfd还是普通的fd
                if (_listensock->Sockfd() == _select_array[i])
                {
                    // 此时可以accept了，一定不会等了
                    Accepter();
                }
                else
                {
                    HanderIO(i);
                }
            }
        }
    }

    void Loop()
    {
        while (true)
        {
            // 设置文件描述符
            fd_set rfds;
            FD_ZERO(&rfds);
            int max_fd = gdefaultfd;
            for (int i = 0; i < gnum; i++)
            {
                if (_select_array[i] != gdefaultfd)
                {
                    FD_SET(_select_array[i], &rfds);
                    if (_select_array[i] > max_fd)
                    {
                        max_fd = _select_array[i];
                    }
                }
            }
            struct timeval timeout = {30, 0};
            int n = ::select(max_fd + 1, &rfds, nullptr, nullptr, nullptr);
            switch (n)
            {
            case 0:
                LOG(DEBUG, "time out, %d.%d\n", timeout.tv_sec, timeout.tv_usec);
                break;
            case -1:
                LOG(ERROR, "select error\n");
                break;
            default:
                LOG(INFO, "haved event ready, n : %d\n", n); // 如果事件就绪，但是不处理，select会一直通知我，直到我处理了！
                HandlerEvent(rfds);
                break;
            }
        }
    }

private:
    uint16_t _port;
    SockSPtr _listensock;
    int _select_array[gnum];
};
